package com.lianrui.app.order.money.impl;

import static com.lianrui.message.IBusinessMessage.BIS_GOODS_NOTEXISTS;
import static com.lianrui.message.IBusinessMessage.BIS_PRODUCT_NOTEXISTS;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.lianrui.app.cart.domain.Cart;
import com.lianrui.app.order.domain.OrderPrice;
import com.lianrui.app.order.money.AbstractCheckout;
import com.lianrui.app.order.money.CheckoutAdapter;
import com.lianrui.commons.exception.BusinessException;
import com.lianrui.commons.tools.Functions;
import com.lianrui.message.ConfigureMessageFactory;

/**
 * 功能描述：默认结算服务
 * 
 * @author LJQ
 * 
 * <br>2016年1月15日 下午3:11:44
 */
@Service("defaultCheckout")
public class DefaultCheckout extends AbstractCheckout {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCheckout.class);
	
	@Override
	public OrderPrice onCheckout(OrderPrice orderPrice) throws BusinessException {
		Double actPrice = 0D, unactPrice = 0D;
		@SuppressWarnings("unchecked")
		List<Cart> params = (List<Cart>) getParams().get(CheckoutAdapter.CKOUT_PARAM_CARTS);
		for (Cart cart : params) {
			if (cart.getProduct() == null) {
				throw new BusinessException(BIS_PRODUCT_NOTEXISTS, LOGGER);
			}
			if (cart.getProduct().getGoods() == null) {
				throw new BusinessException(BIS_GOODS_NOTEXISTS, LOGGER);
			}
			
			int leiNum = Integer.parseInt(cart.getProduct().getGoods().getDefault_count_number());
			Double coupPrice = cart.getProduct().getPrice() + (cart.getProduct().getGoods().getLeiprice() * leiNum);			
			if(cart.getProduct().getPrice().doubleValue() > 0)
				actPrice = Functions.add(actPrice, Functions.mul(cart.getNum(), coupPrice));
			
			if(cart.getProduct().getPrice().doubleValue() == coupPrice)
				unactPrice = Functions.add(unactPrice, Functions.mul(cart.getNum(), coupPrice));
			if(leiNum > 10){
				unactPrice += Functions.mul(leiNum - ConfigureMessageFactory.LEI_NUM_BASIS, cart.getProduct().getGoods().getLeiprice());
			}
			//加上官方价
			unactPrice += Functions.add(unactPrice, cart.getProduct().getCost());
		}
		
		Double couponPrice = unactPrice;// 优惠后的价格
		orderPrice.setGoodsPrice(Functions.add(actPrice, unactPrice)); // 原金额
		orderPrice.setOrderPrice(Functions.add(actPrice, couponPrice));// 商品优惠优惠后的价格

		return orderPrice;
	}

}
